'use strict'
import EventEmitter from './EventEmitter'
export default class RoomData extends EventEmitter {
  constructor (platform, roomId) {
    super()
    this.platform = platform
    this.roomId = roomId
    this.gift = {}
    this.data = {
      users: 0,
      msgs: 0,
      chat: 0,
      coins: 0, // '鱼翅合计' : '猫币合计'
      gifts: 0,
      time: 0,
      online: 0,
      count: {},
      title: this.platform === 'dy' ? '鱼翅合计' : '猫币合计',
      startTime: this._getTime(),
      state: {
        code: 0,
        msg: '连接中'
      }
    }
    this.info = {}
    this.users = new Map()
    this.chatMessages = []
    this.chart = {
      users: [],
      msgs: [],
      chat: [],
      coins: [],
      gifts: [],
      online: [],
      time: []
    }
    this.chartTimer = null
    this.chartStr = ['users', 'msgs', 'chat', 'coins', 'gifts', 'online']
    this.colors = ['#11cd6e', '#56abe4', '#9d55b8', '#ea8010', '#eb4f38', '#33475f', '#00bb9c', '#f4c600', '#000000']
    this.chartTitle = {
      'users': {
        label: '人数变动',
        color: this.colors[0]
      },
      'msgs': {
        label: '弹幕总计',
        color: this.colors[1]
      },
      'chat': {
        label: '发言人数',
        color: this.colors[2]
      },
      'coins': {
        label: this.platform === 'panda' ? '猫币总计' : '鱼翅总计',
        color: this.colors[3]
      },
      'gifts': {
        label: '礼物总计',
        color: this.colors[4]
      },
      'online': {
        label: '观看人数',
        color: this.colors[5]
      }
    }
  }
  initRoom (info) {
    let gift = info.gift
    for (let i = 0; i < gift.length; i++) {
      this.gift[gift[i].id] = {
        name: gift[i].name,
        pc: gift[i].pc,
        type: gift[i].type,
        id: gift[i].id
      }
    }
    for (let i = 0; i < gift.length; i++) {
      this.data.count[gift[i].id] = 0
    }
    this.info = {
      avatar: info.avatar,
      roomName: info.room_name,
      roomUrl: (this.platform === 'dy' ? 'https://www.douyu.com/' : 'http://www.panda.tv/') + this.roomId,
      roomId: info.room_id,
      nick: info.owner_name,
      fans: info.fans_num,
      online: info.online,
      weight: info.owner_weight
    }
    if (info.room_status === '2') {
      this.data.state.code = 2
      this.data.state.msg = '未开播'
    } else {
      this.data.state.code = 3
      this.data.state.msg = '直播中'
      this._onTimer()
    }
    for (var i = 0; i < info.gift.length; i++) {
      this.chart[info.gift[i].id] = []
    }
    this.chartTimer = setInterval(this._onChart.bind(this), 1000 * 60)
  }
  update (info) {
    this.info.fans = info.fans_num
    this.info.online = info.online
    this.info.weight = info.owner_weight
    this.data.online = info.online
    if (info.room_status === '2') {
      this.data.state.code = 2
      this.data.state.msg = '未开播'
      clearTimeout(this.timer)
      clearInterval(this.chartTimer)
      this.emit('roomClose')
    } else {
      this.data.state.code = 3
      this.data.state.msg = '直播中'
    }
    this._postMessage()
  }
  _onTimer () {
    this.data.time += 1
    this.timer = setTimeout(this._onTimer.bind(this), 1000)
  }
  _postMessage (isMsg = false, msg) {
    if (RoomData.port && !RoomData.port.disconnect) {
      RoomData.port.postMessage({
        type: isMsg ? 'msg' : 'data',
        data: isMsg ? msg : this
      })
    }
  }
  _getTime () {
    var date = new Date()
    var minut = date.getMinutes()
    return date.getHours() + ':' + (minut >= 10 ? minut : '0' + minut)
  }
  _push (arr, count, time) {
    var num = count
    if (arr.length > 0) {
      var lastObj = arr[arr.length - 1]
      num = count - lastObj.lastNum
    }
    arr.push({
      time: time,
      lastNum: count,
      count: num
    })
  }
  _onChart () {
    var time = this._getTime()
    this.chart.time.push(time)
    for (var key in this.data) {
      if (this.data.hasOwnProperty(key)) {
        if (key === 'count') {
          for (var k in this.data[key]) {
            if (this.data[key].hasOwnProperty(k)) {
              this._push(this.chart[k], this.data[key][k], time)
            }
          }
        } else if (key === 'online') {
          this.chart[key].push({
            time: time,
            count: this.data[key]
          })
        } else if (key === 'users') {
          if (this.chartStr.indexOf(key) > -1) {
            if (this.chart[key].length > 0) {
              this._push(this.chart[key], this.data.online, time)
            } else {
              this.chart[key].push({
                time: time,
                lastNum: this.data.online,
                count: 0
              })
            }
          }
        } else {
          if (this.chartStr.indexOf(key) > -1) {
            this._push(this.chart[key], this.data[key], time)
          }
        }
      }
    }
  }
  getOnLineChart () {
    return this._getChart(['online', 'users'], 'line')
  }
  getContrastChart () {
    return this._getChart(['msgs', 'chat', 'coins', 'gifts'], 'line')
  }
  getGiftChart () {
    let data = {
      labels: [],
      datasets: [{
        data: [],
        backgroundColor: []
      }]
    }
    let index = 0
    for (var key in this.gift) {
      if (this.gift.hasOwnProperty(key)) {
        data.labels.push(this.gift[key].name)
        data.datasets[0].data.push(this.data.count[this.gift[key].id])
        data.datasets[0].backgroundColor.push(this.colors[index])
        index += 1
      }
    }
    return {
      type: 'pie',
      data: data
    }
  }
  _getChart (chartStr, type) {
    var datas = []
    for (var key in this.data) {
      if (this.data.hasOwnProperty(key)) {
        if (key !== 'count') {
          if (chartStr.indexOf(key) > -1) {
            datas.push({
              label: this.chartTitle[key].label,
              fill: false,
              backgroundColor: this.chartTitle[key].color,
              borderColor: this.chartTitle[key].color,
              data: this.chart[key].map(function (item) {
                return item.count
              })
            })
          }
        }
      }
    }
    return {
      type: type,
      data: {
        labels: this.chart.time,
        datasets: datas
      }
    }
  }
  _initUser (data) {
    if (!this.users.has(data.uid)) {
      var user = {
        uid: data.uid,
        ic: data.ic ? 'http://uc.douyutv.com/upload/' + data.ic + '_middle.jpg?rltime' : '',
        level: data.level,
        nn: data.nn,
        msgs: 0, // 发送信息总数
        msgs_lastTime: '',
        coins: 0, // 总鱼翅数量
        coins_lastTime: '',
        gifts: 0, // 赠送礼物次数
        gifts_lastTime: ''
      }
      for (var key in this.gift) {
        if (this.gift.hasOwnProperty(key)) {
          user[this.gift[key].id] = 0
          user[this.gift[key].id + '_lastTime'] = ''
        }
      }
      this.users.set(data.uid, user)
      return true
    }
    return false
  }
  close () {
    this.data.state.code = 2
    this.data.state.msg = '未开播'
    clearTimeout(this.timer)
    clearInterval(this.chartTimer)
  }
  uenter (data) {
    this.data.users += 1
    this._initUser(data)
    this._postMessage()
  }
  chatmsg (data) {
    if (this.chatMessages.length > 500) {
      this.chatMessages.splice(0, 1)
    }
    this.chatMessages.push(data)
    this.data.msgs += 1
    if (this._initUser(data)) {
      this.data.chat += 1
    }
    let user = this.users.get(data.uid)
    user.msgs += 1
    user.msgs_lastTime = data.serverdate
    this._postMessage()
    data.platform = this.platform
    this._postMessage(true, data)
  }
  dgb (data) {
    this._initUser(data)
    this.data.gifts += 1
    let user = this.users.get(data.uid)
    user.gifts += 1
    user.gifts_lastTime = data.serverdate
    this.data.count[data.gfid] += data.gfid === '1' ? parseInt(data.count, 10) : 1
    user[data.gfid] += data.gfid === '1' ? parseInt(data.count, 10) : 1
    user[data.gfid + '_lastTime'] = data.serverdate
    var self = this
    this.data.coins = this._compute(function (id) {
      return self.data.count[id]
    })
    user.coins = this._compute(function (id) {
      return user[id]
    })
    this._postMessage()
  }
  _compute (fn) {
    var count = 0.0
    for (var key in this.gift) {
      if (this.gift.hasOwnProperty(key)) {
        if (this.gift[key].type === '2') {
          count += this.gift[key].pc * fn(this.gift[key].id)
        }
      }
    }
    return count
  }
  filter (field) { // 排序
    let users = Array.from(this.users).map((user) => {
      return user[1]
    })
    users.sort(function (a, b) {
      return b[field] - a[field]
    })
    return users.slice(0, 100)
      .filter(function (item) {
        if (item[field] > 0) {
          return true
        }
        return false
      })
  }
}
